package com.chem.lems.repository;

import com.chem.lems.entity.Equipment;
import com.chem.lems.entity.Record;
import com.chem.lems.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

public interface EquipmentRepository extends JpaRepository<Equipment,String>, JpaSpecificationExecutor<Equipment> {
    // 模糊查询
    @Query(value = "SELECT * FROM elms_equip t WHERE t.equip_name like %?1%",nativeQuery = true)
    Page<Equipment> findByNameLike(String content, PageRequest pageRequest);

    @Query(value = "SELECT user_id FROM elms_user_equip t WHERE  t.equip_id =?1",nativeQuery = true)
    String findUserIdByequipId(String roleId);

    // 更新用户的角色
    @Transactional
    @Modifying
    @Query(value = "UPDATE elms_equip SET equip_state = ?1 WHERE equip_id = ?2",nativeQuery = true)
    Integer updataEquipState(Integer equipState, String equipId);
    // 更新预约功能 用户-设备管理信息
    @Transactional
    @Modifying
    @Query(value = "INSERT INTO `elms_user_equip`(`user_id`, `equip_id`) VALUES (?1, ?2)",nativeQuery = true)
    void addApplyInfo(String userId,  String equipId);

    // 分页查询 待审核设备
    @Query(value = "SELECT * FROM elms_equip t WHERE t.equip_state = ?1",nativeQuery = true)
    List<Equipment> getRecordList(int equipState, Integer page, Integer size);

    @Transactional
    @Modifying
    @Query(value = "DELETE FROM elms_user_equip t WHERE t.user_id=?1 AND t.equip_id=?2",nativeQuery = true)
    void deleteUserEquip(String userId, String equipId);

    // 查询设备创建时间
    @Query(value = "SELECT create_time FROM elms_equip",nativeQuery = true)
    List<String> findAllDate();

    // 查询设备创建时间
    @Query(value = "SELECT create_time FROM elms_equip",nativeQuery = true)
    List<Date> findAllDateObj();

    // 根据设备状态码查询设备
    @Query(value = "SELECT * FROM elms_equip t WHERE  t.equip_state =?1",nativeQuery = true)
    List<Equipment> findAllByState(int stateCode);

    // 根据设备状态码查询设备
    @Query(value = "SELECT equip_id FROM elms_equip t WHERE  t.equip_state =?1",nativeQuery = true)
    List<String> findIdByState(int stateCode);
}
